package com.ias.agdis_r.activity.task;

import java.util.List;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.bean.message.SummaryTemplates;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.bean.task.TaskProcess;
import com.ias.agdis_r.util.network.HttpUtil;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.SubmittaskprocssRequest;
import com.ias.agdis_r.terminalmanager.restful.task.vo.SubmitTaskProcessRequestVO;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.TaskUtil;
import com.ias.agdis_r.view.control.EditorTextClear;


/**
 * 航班报告总结界面
 * @author guoxr
 *
 */
public class FlightSummaryActivity extends BaseActivity implements
		OnClickListener {
	private SubmittaskprocssRequest submittaskprocssRequest;
	private static final String Tag = "FlightSummaryView--->";
	private TextView txt_flight_no;
	private EditorTextClear edit_content;

	private Button btn_left;
	private Button btn_right;
	private String title;
	private TextView showmark;

	private ListView lv_msg;
	private String sTnb;
	private String oldPid;
	private String newPid;
	private Task task = null;
	private TaskProcess excuteNode = null;
	private ArrayAdapter<String> mSchedule = null;
	private ActionBar actionBar;
	private int selected = -1;// 选中的记录索引
	private int firstVisiblePosition = 0;
	private Intent intent;
	private AlertDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_flightsummary);
		intent = getIntent();
		actionBar = getActionBar();
		initActionBarFlightSummary();
		init();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (task.getPID().equals(MessageModel.TCXX)
				|| task.getPID().equals(MessageModel.TEND)
				|| task.getPID().equals(MessageModel.TRJT)) {
			finish();
		}
		// 获取intent传值
		oldPid = S.valueOf(intent.getExtras().getString(MessageModel.PID));
		task = DataManager.getInstance().getReceiveTask(sTnb);
		if (task == null) {
			task = DataManager.getInstance().getWorkTask(sTnb);
		}
		if (task == null) {
			finish();
			return;
		}
		// 获取本次取到的当前节点
		newPid = task.getPID();
		// 如果界面上次加载数据的PID不为空&&PID与本次比较发生变更(发生节点变更)
		if (S.isNotEmpty(oldPid) && !oldPid.equals(newPid)) {
			finish();
			return;
		}
	}

	private void init() {
		// TODO Auto-generated method stub

		btn_left = (Button) findViewById(R.id.bottom_button1);
		btn_right = (Button) findViewById(R.id.bottom_button2);
		txt_flight_no = (TextView) findViewById(R.id.txt_flight_no);
		edit_content = (EditorTextClear) findViewById(R.id.edit_content);
		lv_msg = (ListView) findViewById(R.id.listview_flight_summary);
		showmark = (TextView) findViewById(R.id.showmark);
		btn_left.setOnClickListener(this);
		btn_right.setOnClickListener(this);
		// btn_confirm = (TextView) findViewById(R.id.bottom_button1);
		// btn_cancel = (TextView) findViewById(R.id.bottom_button2);
		// btn_confirm.setText("确定");
		// btn_cancel.setText("取消");
		//
		// title = (TextView) alert.findViewById(R.id.alert_title);
		btn_left.setText(getString(R.string.back));
		btn_right.setText(getString(R.string.confirm));
		loadData();
	}

	public void loadData() {
		// 获取intent传值
		sTnb = intent.getExtras().getString(MessageModel.TNB);
		oldPid = intent.getExtras().getString(MessageModel.PID);
		task = DataManager.getInstance().getReceiveTask(sTnb);
		if (task == null) {
			task = DataManager.getInstance().getWorkTask(sTnb);
		}
		if (task == null) {
			finish();
			return;
		}
		String excutePid = S
				.valueOf(intent.getExtras().getString("EXCUTE_PID"));
		// 如果PID有值(接受/拒绝)，获取对应节点
		if (S.isNotEmpty(excutePid)) {
			excuteNode = task.getProcess(excutePid);
		}
		// 获取下一个节点
		else {
			excuteNode = TaskUtil.getNextTaskNode(task);
		}
		if (excuteNode == null) {
			finish();
			return;
		}

		title = getString(R.string.FSA_1) + excuteNode.getPCNM() + getString(R.string.FSA_2);
		showmark.setText(excuteNode.getPCNM() + getString(R.string.FSA_3));
		txt_flight_no.setText(task.getTaskInfo().getFLN());
		try {
			SummaryTemplates summaryTemplates = JavaBeanManager.getInstance()
					.getSummaryTemplates();
			if (summaryTemplates != null && summaryTemplates.size() > 0) {
				List<String> msgList = summaryTemplates.get(excuteNode
						.getPCID());
				if (msgList != null && msgList.size() > 0) {
					mSchedule = new ArrayAdapter<String>(
							FlightSummaryActivity.this,
							R.layout.adpater_msg_send, R.id.content, msgList);
					lv_msg.setAdapter(mSchedule);
					lv_msg.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							view.requestFocusFromTouch();
							firstVisiblePosition = 0;
							parent.setSelection(position);
						}
					});
					lv_msg.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> parent,
								View view, int position, long arg3) {
							firstVisiblePosition = parent
									.getFirstVisiblePosition();
							int index = position
									- parent.getFirstVisiblePosition();
							selected = index;
						}

						@Override
						public void onNothingSelected(AdapterView<?> parent) {

						}
					});
					lv_msg.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
						@Override
						public void onItemSelected(AdapterView<?> arg0,
								View arg1, int arg2, long arg3) {
							// TODO Auto-generated method stub
							System.out.println("=======onItemSelected======");
							String selectText = (String) arg0.getAdapter()
									.getItem(arg2);
							edit_content.setText(selectText);
						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
							// TODO Auto-generated method stub
						}
					});
				} else {
					cleanData();
				}
			}
		} catch (Exception e) {
			Log.i("error", Tag + "bindData():" + e.toString());
			e.printStackTrace();
		}
	}

	public void cleanData() {
		if (mSchedule != null) {
			mSchedule.clear();
			mSchedule.notifyDataSetChanged();
		}
		if (edit_content != null) {
			edit_content.setText("");
		}
	}

	private void initActionBarFlightSummary() {
		// TODO Auto-generated method stub
		actionBar.setCustomView(LayoutInflater.from(FlightSummaryActivity.this)
				.inflate(R.layout.actionbar_back_and_home, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		TextView title = (TextView) findViewById(R.id.txt_title);
		title.setText(R.string.FlightSummaryActivity);
		ImageView back = (ImageView) findViewById(R.id.action_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		ImageView home = (ImageView) findViewById(R.id.action_home);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(FlightSummaryActivity.this, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
	}

	/**
	 * 执行任务
	 */
	private void onExcute() {
		if (excuteNode != null) {
			// 生成执行任务消息
			// String newTaskProcInfo = MessageManager.getInstance()
			// .getTaskMessage(task.getTNB(), excuteNode.getPCID(),
			// edit_content.getText().toString());
			initTRPT(task.getTNB(), excuteNode.getPCID(), edit_content
					.getText().toString());
			HttpUtil.getInstance().sendRequest(submittaskprocssRequest, MessageModel.TRPT,
					true);
		}
	}

	private void initTRPT(String tnb, String pid, String rmk) {
		// TODO 装填数据，测试使用
		submittaskprocssRequest = new SubmittaskprocssRequest();
		SubmitTaskProcessRequestVO submittaskprocssrequestVO = new SubmitTaskProcessRequestVO();
		submittaskprocssrequestVO.setIFM("");
		submittaskprocssrequestVO.setPID(pid);
		submittaskprocssrequestVO.setRMK(rmk);
		submittaskprocssrequestVO.setSDT(S.getNowTime());
		submittaskprocssrequestVO.setTNB(tnb);
		submittaskprocssrequestVO.setTST("S");
		submittaskprocssRequest
				.setSubmittaskprocssRequestVO(submittaskprocssrequestVO);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == btn_left) {
			finish();
		} else if (v == btn_right) {
			if (S.isEmpty(edit_content.getText().toString())) {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_TASK, getString(R.string.writeInfo), false);
			} else if (dialog == null || !dialog.isShowing()) {
				dialog(title);
			}
		}
	}

	/**
	 * 提示dialog
	 */
	private void dialog(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				FlightSummaryActivity.this);
		builder.setTitle(getString(R.string.prompt));
		builder.setMessage(message);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				onExcute();
				dialog.dismiss();
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		dialog = builder.create();
		dialog.show();
	}

	@Override
	protected void operateResponseSucess(String serviceId, BaseResponse response) {
		// TODO Auto-generated method stub
		if (MessageModel.TRPT.equals(serviceId)) {
			if (task != null) {
				// 获取当前节点名称
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_TASK,
						getString(R.string.report) + task.getProcess(task.getPID()).getPCNM() + getString(R.string.succeed), false);
			}
			setResult(RESULT_OK);
			finish();
		}
	}

	@Override
	protected void updateUI(String tag) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void updateUI(String tag, String tnb) {
		if (tag.equals(MessageModel.REFRESH)) {
			if (tnb.equals(sTnb)) {
				if(MessageModel.TEND.equals(task.getPID()) || MessageModel.TCXX.equals(task.getPID()) || task.getPID().equals(MessageModel.TRJT)){
					finish();
				}
			}
		}
	}
}
